package com.soooft.tickey.security.core.support;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description
 * @Author: Fanxl
 * @Date: Created in 2017/9/29 21:15
 */
public class MD5Util {

    /**
     * md5加密
     *
     * @param password 明文
     *
     * @return 密文 (传入正常String返回加密后的String)
     */
    public static String md5(String password, String key) {
        key = key.toUpperCase();
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
            msgDigest.update(password.getBytes("GBK")); // 这里必需强制指定编码，否则linux与Windows下得到的值不一样
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] bytes = null;
        try {
            bytes = msgDigest.digest(key.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (bytes == null) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }

        byte tb;
        char low;
        char high;
        char tmpChar;

        String md5Str = new String();

        for (int i = 0; i < bytes.length; i++) {
            tb = bytes[i];

            tmpChar = (char) ((tb >>> 4) & 0x000f);

            if (tmpChar >= 10) {
                high = (char) (('a' + tmpChar) - 10);
            } else {
                high = (char) ('0' + tmpChar);
            }

            md5Str += high;
            tmpChar = (char) (tb & 0x000f);

            if (tmpChar >= 10) {
                low = (char) (('a' + tmpChar) - 10);
            } else {
                low = (char) ('0' + tmpChar);
            }

            md5Str += low;
        }
        return md5Str;
    }

    public static void main(String[] args){
        String str = MD5Util.md5("111111", "admin");
        System.out.println(str);

        Md5PasswordEncoder md5PasswordEncoder =  new Md5PasswordEncoder();
        boolean result = md5PasswordEncoder.isPasswordValid("d4db2ba11114c191cd86070367c9b60f", "111111", "admin");
        System.out.println(result);
    }
}
